const mysql = require('mysql2/promise');

/**
 * 清理数据库中的外键约束
 */
async function cleanForeignKeys() {
    console.log('🧹 清理数据库中的外键约束...');

    const connection = await mysql.createConnection({
        host: '43.143.253.188',
        port: 3306,
        user: 'nextjs',
        password: 'yEAiRE2jcxTyRBy5',
        database: 'nextjs',
        timezone: '+08:00'
    });

    try {
        // 禁用外键检查
        await connection.execute("SET FOREIGN_KEY_CHECKS=0");
        console.log('✅ 已禁用外键检查');

        // 查询所有外键约束
        const [constraints] = await connection.execute(`
      SELECT 
        CONSTRAINT_NAME,
        TABLE_NAME
      FROM 
        INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
      WHERE 
        REFERENCED_TABLE_SCHEMA = 'nextjs' 
        AND REFERENCED_TABLE_NAME IS NOT NULL
      ORDER BY CONSTRAINT_NAME
    `);

        console.log(`📋 找到 ${constraints.length} 个外键约束需要清理`);

        // 删除所有外键约束
        for (const constraint of constraints) {
            try {
                await connection.execute(`ALTER TABLE \`${constraint.TABLE_NAME}\` DROP FOREIGN KEY \`${constraint.CONSTRAINT_NAME}\``);
                console.log(`✅ 已删除外键约束: ${constraint.CONSTRAINT_NAME} (表: ${constraint.TABLE_NAME})`);
            } catch (error) {
                console.log(`⚠️ 删除外键约束失败: ${constraint.CONSTRAINT_NAME} - ${error.message}`);
            }
        }

        // 重新启用外键检查
        await connection.execute("SET FOREIGN_KEY_CHECKS=1");
        console.log('✅ 已重新启用外键检查');

        console.log('\n🎉 外键约束清理完成！');

    } catch (error) {
        console.error('❌ 清理外键约束失败:', error.message);
        throw error;
    } finally {
        await connection.end();
    }
}

// 执行清理
cleanForeignKeys()
    .then(() => {
        console.log('✅ 外键约束清理脚本执行完成');
        process.exit(0);
    })
    .catch((error) => {
        console.error('💥 外键约束清理脚本执行失败:', error.message);
        process.exit(1);
    });
